package com.platform.comm.common.service;


import com.platform.comm.service.ICommBatchInfoBiz;
import com.platform.comm.common.batch.ComBatchContext;
import com.platform.comm.util.DateTimeUtil;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * description: 通用批量上传下载操作
 *
 * @author lx
 */
@Service
@Scope("prototype")
public class ComBatchImportService {
    private final JobLauncher jobLauncher;
    private final Job comBatchJob;
    private final ComBatchContext context;
    private final ICommBatchInfoBiz dirBatchInfoBiz;

    public ComBatchImportService(JobLauncher jobLauncher, Job comBatchJob,
                                 ComBatchContext context, ICommBatchInfoBiz dirBatchInfoBiz) {
        this.jobLauncher = jobLauncher;
        this.comBatchJob = comBatchJob;
        this.context = context;
        this.dirBatchInfoBiz = dirBatchInfoBiz;
    }


    public void startImportJob(Map<String, String> parameterMap) throws Exception {
        initImportContext(parameterMap);
        JobExecution jobExecution = jobLauncher.run(comBatchJob, buildImportJobParameters());
        jobExecution.getExecutionContext().put("config", context);
        if (jobExecution.getStatus().isRunning()) {
            dirBatchInfoBiz.createExportDirJob(context.getNewCommBatchEntity(jobExecution.getJobId()));
        }
    }

    private JobParameters buildImportJobParameters() {
        String jobName = context.getCommDataInfoEntity().getFileName()+ ":" +
                DateTimeUtil.toStdDateStr(context.getCommDataInfoEntity().getUploadDate());
        return new JobParametersBuilder()
                .addLong("time", System.currentTimeMillis())
                .addString("jobName",jobName)
                .toJobParameters();
    }

    private void initImportContext(Map<String, String> parameterMap) {
        context.bindCommonData(parameterMap.get("importId"))
                .buildConfig(parameterMap.get("moduleName"))
                .bindParams(parameterMap).build();
    }

}
